<?php

/*
 * @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @Date: 2022-03-28 18:39:15
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-03-28 18:42:35
 * @Description: File Description
 */

namespace rainlee\auth\jwt;

use InvalidArgumentException;
use think\facade\Config;

class JwtManager
{
    protected $guards = [];

    /**
     * 获取JWT看守器类
     * 
     * @param  string|null  $name
     * @return 
     */
    public function guard($name = null)
    {

        $name = $name ?: $this->getDefaultGuard();
        if (is_null($name)) {
            throw new InvalidArgumentException(sprintf(
                'Unable to resolve NULL guard for [%s].',
                static::class
            ));
        }

        return $this->guards[$name] ?? $this->guards[$name] = $this->resolve($name);
    }

    /**
     * 解析配置文件
     * 
     * @return array|null
     */
    protected function resolveConfig($name)
    {
        if ($config = Config::get('jwt.guards.' . $name)) {
            return new JwtConfig($config);
        }
        return null;
    }

    /**
     * 创建处理程序
     *
     * @param string $name
     * @return mixed
     *
     */
    protected function resolve(string $name)
    {
        $config = $this->resolveConfig($name);

        if (is_null($config)) {
            throw new InvalidArgumentException("JWT guard [{$name}] is not defined.");
        }

        return new JwtHandler($name, $config);
    }

    /**
     * 获取默认看守器
     * 
     * @return string
     */
    protected function getDefaultGuard()
    {
        return Config::get('jwt.default');
    }

    /**
     * 动态调用
     * @param string $method
     * @param array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return $this->guard()->$method(...$parameters);
    }
}
